package com.fanco.learn_datastruct_leetcode.leetcode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。
 * @author qiaowang 2021/7/6
 */
public class Day21 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int [] traps = {0,1,0,2,1,0,1,3,2,1,2,1};
        System.out.println(solution.trap(traps));
    }

    private static class Solution {
        public int trap(int[] height) {
            int ans = 0;
            Deque<Integer> stack = new LinkedList<Integer>();
            int n = height.length;
            for (int i = 0; i < n; ++i) {
                while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                    int top = stack.pop();
                    if (stack.isEmpty()) {
                        break;
                    }
                    int left = stack.peek();
                    int currWidth = i - left - 1;
                    int currHeight = Math.min(height[left], height[i]) - height[top];
                    ans += currWidth * currHeight;
                }
                stack.push(i);
            }
            return ans;

        }
    }
}
